<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Cookbook;
use App\Models\CookbookAdvView;
use App\Models\Star;
use App\Models\UserViewHistory;
use App\Services\OrderService;
use App\Services\UserViewHistoryService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class CookbookController extends BaseController
{

    public $model = Cookbook::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $title = $request->input('title');
        $category_id = $request->input('category_id');
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');
        //观看历史
        $is_my_history = $request->input('is_my_history');
        $is_my = $request->input('is_my', 0);
        $type = $request->input('type', 0);
        $is_relate_rec = $request->input('is_relate_rec', 0);
        $cookbook_id = $request->input('cookbook_id');
        $parent_category_id = $request->input('parent_category_id');

        $is_on = 1; //上架
        $is_vip = $request->input('is_vip');
        $fields = ['id', 'title', 'short_title', 'is_vip', 'video_url', 'short_video_url', 'long_time', 'difficulty', 'category_id','type'];

        $merchant_id = 0;
        if ($is_my) {
            $merchant_id = $this->getUser()->relate_merchant_id ?? 0;
        }

        $list = Cookbook::select($fields)->title($title)
            ->category($category_id)
            ->with('category')
            ->when($type, function ($q) use($type) {
                $q->where('type', $type);
            })
            ->parentCategory($parent_category_id)
            ->merchantId($merchant_id)
            ->when($is_my_history, function ($q) {
                $q->whereHas('view_history', function ($qr) {
                    $user_id = $this->getUserId();
                    if ($user_id)
                        $qr->where('user_id', $user_id);
                });
            })
            ->isOn($is_on)->when($is_vip, function ($q)use($is_vip) {
//                $q->where('is_vip', '=', $is_vip);
            });

        if ($is_relate_rec) {
            if (!$cookbook_id)
                return $this->failed('缺少cookbook_id参数');
            $list = $list->where('id', '!=', $cookbook_id)->inRandomOrder()->paginate(\request('per_page', 2));
        } else {
            $list = $list->orderBy($order_by_key, $order_by_value)->orderBy("id", "desc")
                ->paginate(\request('per_page', 20));
        }
        return $this->paginate($list);
    }

    public function info(Request $request) {
        $id = \request("id");
        if (!$id) {
            return $this->failed("参数ID不存在");
        }
        $user = $this->getUser();
        if ($user) {
            $cook = Cookbook::userStar($user->id)->with('category')->with(['product' => function($q) {
                $q->select('title', 'mall_products.id', 'image_url', 'amount', 'vip_amount');
            }])->withCertain('merchant', ['contact'])->find($id);
            if (!$cook)
                return $this->failed("食谱不存在");
            $cook->is_buy = false;
            if ($cook->is_on == 0 || $cook->audit_status != 1)
                return $this->failed("商品已下架");

            $cook->user = $user->setVisible(['is_vip', 'vip_expired_at']);
        } else {
            $cook = Cookbook::userStar(0)->with('category')->withCertain('merchant', ['contact'])->find($id);
            $cook->is_buy = false;
            $cook->user = null;
        }
        return $this->success($cook);
    }

    public function viewHistory(Request $request) {
        $title = $request->input('title');
        $user = $this->getUser();
        $list = UserViewHistory::where('user_id', $user->id)->when($title, function ($q) use($title){
            $q->whereHas('cookbook', function ($query) use($title){
               $query->where('title', 'like', "%$title%");
            });
        })->withCertain('cookbook', ['title','short_video_url', 'short_title', 'video_url', 'type'])
            ->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }


    public function collect(Request $request) {
        $this->validate($request, [
            'user_id' => 'required'
        ]);
        $user_id = \request('user_id');
        $list = Star::where('user_id', $user_id)->where('type', 1)
            ->withCertain('cookbook', ['title','short_video_url', 'short_title','video_url', 'type'])
            ->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

    public function viewAdv(Request $request) {
        $user = $this->getUser();
        $cache_key = 'view_adv_user_' . $user->id;
        if (Redis::setnx($cache_key, 1)) {
            Redis::expire($cache_key, 2);
            try {
                $input = $request->input();
                $is_finish = $input['is_finish'] ?? 0;
                CookbookAdvView::create([
                    'benefit_user' => $user->benefit_user,
                    'user_id' => $user->id,
                    'merchant_id' => $user->rec_merchant_id,
                    'cookbook_id' => $input['cookbook_id'],
                    'is_finish' => $is_finish,
                    'month' => date('Ym')
                ]);
                $is_finish && UserViewHistoryService::store($user->id, $input['cookbook_id']);
                return $this->success([]);
            } catch (\Exception $e) {
                \Log::error($e);
                Redis::del($cache_key);
                return $this->failed($e->getMessage());
            }
        }
    }


}

